package com.ymy.thinking.in.spring.dependency.injection;

import com.ymy.thinking.in.spring.dependency.injection.annotation.UserGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

import java.util.List;

/**
 * {@link Qualifier} 限定注入案例
 *
 * @author Ringo
 * @date 2021/9/30 14:13
 * @see Qualifier
 * @see UserGroup
 */
public class QualifierAnnotationDependencyInjectionDemo {

    @Autowired
    private User user;   // user2 -> @Primary

    @Autowired
    @Qualifier("user1")  // 指定 Bean name
    private User namedUser;

    // 整体应用上下文存在 4 个 User 类型的 Bean
    // user1
    // user2
    // user3 -> @Qualifier
    // user4 -> @Qualifier

    @Autowired
    private List<User> allUsers;    // 注入所有的 User 类型的 Bean

    @Autowired
    @Qualifier
    private List<User> qualifiedUsers; // 4 Beans = user1 + user2 + user3 + user4

    @Autowired
    @UserGroup
    private List<User> groupedUsers; // 2 Bean = user3 + user4

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext =
                new AnnotationConfigApplicationContext();
        applicationContext.register(QualifierAnnotationDependencyInjectionDemo.class);
        applicationContext.refresh();

        QualifierAnnotationDependencyInjectionDemo demo =
                applicationContext.getBean(QualifierAnnotationDependencyInjectionDemo.class);

        System.out.println("demo.user = " + demo.user);
        System.out.println("demo.namedUser = " + demo.namedUser);
        System.out.println("demo.allUsers = " + demo.allUsers);
        System.out.println("demo.qualifiedUsers = " + demo.qualifiedUsers);
        System.out.println("demo.groupedUsers = " + demo.groupedUsers);
    }

    @Bean
    @Qualifier
    public User user1() {
        return new User("zs", 19);
    }

    @Bean
    @Primary
    @Qualifier
    public User user2() {
        return new User("ls", 20);
    }

    @Bean
    @UserGroup  // 进行逻辑分组
    public User user3() {
        return createUser("007");
    }

    @Bean
    @UserGroup // 进行逻辑分组
    public User user4() {
        return createUser("008");
    }

    // 工厂方法
    public static User createUser(String name) {
        User user = new User();
        user.setName(name);
        return user;
    }

}
